﻿using System;
using System.Windows.Forms;
using System.Diagnostics;
using Microsoft.Win32;



namespace CSP.Package.Controls
{
    public partial class CRMCustomizations : UserControl, IInstallationControl
    {

        private const string _executionPath = @"CRMCustomizations\csp.crmdeployer.exe";

        public CRMCustomizations()
        {
            InitializeComponent();
            FillDefaults();
        }

        #region IInstallationControl Members

        private Installer _form;
        public Installer GetForm()
        {
            return _form;
        }

        public void SetForm(Installer installer)
        {
            _form = installer;
        }


        public bool Next()
        {
          try
          {
            if (ValidateInputs())
            {

              GetForm().AddToLog("----------------------------------------------");
              GetForm().AddToLog(labels.CspInstallLog_CSPCRMCustomizationsStarted);

              GetForm().AddToLog("----------------------------------------------");
              GetForm().AddToLog(labels.CspInstallLog_CreatingRegistryEntries);
              CreateRegistryEntries();

              Process process = new Process();
              process.StartInfo.CreateNoWindow = false;
              process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

              string crmUserName = String.Format(@"{0}\{1}", txbDomain.Text, txbUsername.Text);

              process.StartInfo.FileName = _executionPath;
              string arguments = string.Format(@"-s {0} -o {1} -u {2}", txbCrmServerUrl.Text, txbOrganization.Text, crmUserName);

              // DASB 16/01/2009
              // Deleted -lc parameter: language code of installer is now on csp.crmdeployer.exe.config
              GetForm().AddToLog("   " + labels.CspInstallLog_Arguments + ": " + arguments);

              process.StartInfo.WorkingDirectory = "CRMCustomizations";
              process.StartInfo.CreateNoWindow = true;
              process.StartInfo.Arguments = arguments;
              process.StartInfo.UseShellExecute = false;
              process.StartInfo.RedirectStandardOutput = true;
              process.StartInfo.RedirectStandardError = true;
              process.Start();
              string error = process.StandardError.ReadToEnd();
              string output = process.StandardOutput.ReadToEnd();
              process.WaitForExit();
              if (error != string.Empty)
                throw new ApplicationException(error);

              //CSP.Core.RegistryAccess.CreateStringProperty(Registry.LocalMachine,
              //  CSP.Core.Constants
              //  "CSPIntranetWebApplication", 
              //  GetWebApplicationUrl());

              GetForm().AddToLog(output);
              return true;
            }
            else
            {
              return false;
            }
          }
          catch (Exception ex)
          {
            this.GetForm().ShowException(ex);
            throw ex;
          }
        }

        public void Previous()
        {
            
        }

        public void Skip()
        {
            
        }

        #endregion

        private void CRMCustomizations_Load(object sender, EventArgs e)
        {
            TranslateLiterals();
        }

        private void TranslateLiterals()
        {
            richTextBox1.Text = CSP.Package.labels.CRMCustomizations_Intro;

            groupBox1.Text = CSP.Package.labels.CRMServer_GroupBox;
            groupBox1.Text = CSP.Package.labels.CRMCredentials_GroupBox;

            label5.Text = CSP.Package.labels.Url_Label;
            label6.Text = CSP.Package.labels.Organization_Label;
            label4.Text = CSP.Package.labels.Domain_Label;
            label7.Text = CSP.Package.labels.Username_Label;
            label3.Text = CSP.Package.labels.Password_Label;

            //this.btnTestConnection.Text = CSP.Package.labels.TestConnection_Label;
        }

        private void FillDefaults()
        {
          txbUsername.Text = Environment.UserName;
          txbDomain.Text = Environment.UserDomainName;
          if (RegistryAccess.PropertyExists(Registry.LocalMachine, @"SOFTWARE\Microsoft\MSCRM", "ServerUrl"))
          {
            string strServerUrl = RegistryAccess.GetStringProperty(Registry.LocalMachine, @"SOFTWARE\Microsoft\MSCRM", "ServerUrl");
            Uri crmServerUri = new Uri(strServerUrl);
            txbCrmServerUrl.Text = String.Format("{0}://{1}:{2}", crmServerUri.Scheme, crmServerUri.Host, crmServerUri.Port);
            txbOrganization.Text = "CSP";
          }
        }



        private bool ValidateInputs()
        {
          TextBox[] txbs = new TextBox[] { txbCrmServerUrl, txbDomain, txbOrganization, txbPassword, txbUsername };
          foreach (TextBox txb in txbs)
            if (!ValidateTextBoxNotTempty(txb))
              return false;
          if (!ValidateUri(txbCrmServerUrl))
            return false;
          //if (!ValidateCrmConnection())
          //  return false;
          return true;
        }

        private bool ValidateUri(TextBox txb)
        {
          bool success = Uri.IsWellFormedUriString(txb.Text, UriKind.Absolute);
          if (!success)
          {
                string message = labels.CspInstallError_URLNotWellFormed; 
                MessageBox.Show(message, CSP.Package.labels.CspInstallError_Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                txb.Focus();
                txb.Select();
                return false;
          }
          else
            return true;
        }

        private bool ValidateTextBoxNotTempty(TextBox txb)
        {
          if (txb.Text.Length == 0)
          {
                string message = String.Format(labels.CSPInstallError_NoEmpty, txb.Tag);
                MessageBox.Show(message, CSP.Package.labels.CspInstallError_Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                txb.Focus();
                txb.Select();
                return false;
          }
          else
            return true;
        }


        private void CreateRegistryEntries()
        {
          RijndaelCryptography crip = new RijndaelCryptography();
          crip.GenKey();
          crip.Encrypt(txbPassword.Text);
          byte[] encryptedPassword = crip.Encrypted;

          RegistryAccess.CreateStringProperty(Registry.LocalMachine, Constants.CspRegistryKey, "CrmServerUrl", txbCrmServerUrl.Text);
          RegistryAccess.CreateStringProperty(Registry.LocalMachine, Constants.CspRegistryKey, "CrmOrganizationName", txbOrganization.Text);
          RegistryAccess.CreateStringProperty(Registry.LocalMachine, Constants.CspRegistryKey, "CrmUserName", txbUsername.Text);
          RegistryAccess.CreateStringProperty(Registry.LocalMachine, Constants.CspRegistryKey, "CrmUserDomain", txbDomain.Text);
          RegistryAccess.CreateByteArrayProperty(Registry.LocalMachine, Constants.CspRegistryKey, "CSPCryptographyKey", crip.Key);
          RegistryAccess.CreateByteArrayProperty(Registry.LocalMachine, Constants.CspRegistryKey, "CSPCryptographyIV", crip.IV);
          RegistryAccess.CreateByteArrayProperty(Registry.LocalMachine, Constants.CspRegistryKey, "CrmUserPassword", encryptedPassword);
          
        }
    }
}
